package com.brkj.course;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.dgl.sdk.util.FileCache;
import com.dgl.sdk.view.myVideoView.VideoPlayerActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import com.brkj.httpInterface.BaseAjaxParams;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.brkj.model.DS_Comment;
import com.brkj.model.DS_Course;
import com.brkj.download.CourseDownloader;
import com.brkj.main.R;
import com.brkj.util.ConstAnts;
import com.brkj.httpInterface.HttpInterface.HIF_FavoriteCourse;
import com.brkj.httpInterface.HttpInterface.HIF_GetCoumment;
import com.brkj.httpInterface.HttpInterface.HIF_SubmitComment;
import com.brkj.util.ImgShow;
import com.brkj.util.JsonUtil;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.MyApplication;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.WidgetAnim;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class CourseDetailActivity extends BaseActivity{

	@ViewInject(id=R.id.commentListView) ListView commentListView;
	@ViewInject(id=R.id.commentEdit) EditText commentEdit;
	@ViewInject(id=R.id.submit,click="submitComment") Button submit;
	
	private View courseView;
	private ImageView CourseImg;
	private TextView Title;
	private TextView Content;
	private TextView Time;
	private TextView StudyCount;
	
	private final String ALL_COURSE = "0";
	private final String POST_COURSE = "1";
	
	private CommentAdapter commentAdapter;
	private String thisCourseID;
	private View download;
	private View favorite;
	protected List<DS_Comment> commentList = new ArrayList<DS_Comment>();
	private ImageView play;
	private TextView submitTime;
	private TextView comment_num;
	private TextView favorite_num;
	private TextView teacher;
	private View lodingView;

    protected DS_Course course;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		setAnimType(RIGHT_ENTER_LEFT_EXT);
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.course_detail);
		
		setActivityTitle("课程详情");
		setReturnBtn();
		
		initCourse();
		initLodingBar();
        showCourseDetail();

		thisCourseID = Integer.toString(((DS_Course) getIntent().getSerializableExtra("course")).getCourseID());
		getComment(thisCourseID);
		
		commentEdit.clearFocus();
		
		commentListView.addHeaderView(courseView);
		commentListView.addHeaderView(lodingView);
		
		commentAdapter = new CommentAdapter(CourseDetailActivity.this, commentList);
		commentListView.setAdapter(commentAdapter);
		
	}

	private void initCourse() {
		courseView = getLayoutInflater().inflate(
				R.layout.course_detail_course_view, null, false);
		
		CourseImg = (ImageView) courseView.findViewById(R.id.CourseImg);
		play = (ImageView) courseView.findViewById(R.id.play);
		Title = (TextView) courseView.findViewById(R.id.Title);
		Content = (TextView) courseView.findViewById(R.id.Content);
		Time = (TextView) courseView.findViewById(R.id.Time);
		StudyCount = (TextView) courseView.findViewById(R.id.StudyCount);
		download = courseView.findViewById(R.id.download);
		favorite = courseView.findViewById(R.id.favorite);
		submitTime = (TextView) courseView.findViewById(R.id.submitTime);
		comment_num = (TextView) courseView.findViewById(R.id.comment_num);
		favorite_num = (TextView) courseView.findViewById(R.id.favorite_num);
		teacher = (TextView) courseView.findViewById(R.id.teacher);
		
	}
	private void initLodingBar() {
		lodingView = getLayoutInflater().inflate(
				R.layout.loding_bar, null, false);
		
	}

    private String getVideoUrl(String url){

        FileCache fileCache =  new FileCache(this, ConstAnts.DOWNLOAD_COURSE__DIR);

        String localFile = fileCache.getAbsolutePathByUrl(url);

        if(new File(localFile).exists()){
            return localFile;
        }else{
            return url;
        }
    }

    protected void showCourseDetail(){
        course = (DS_Course) getIntent().getSerializableExtra("course");

        showCourse();
    }

	protected void showCourse() {

		Title.setText(course.getTitle());
		Content.setText(course.getContent());
		teacher.setText("讲师姓名：" + course.getTeacher());
		Time.setText("课程时长：" + course.getTime());
		StudyCount.setText("学习(" + course.getStudyCount()+")");
		comment_num.setText("评论(" + course.getCommnetNum()+")");
		favorite_num.setText("收藏(" + course.getFavoriteNum()+")");
		submitTime.setText(course.getSubmitTime());
//		Title.setText(intent.getStringExtra("Title"));
//		Content.setText(intent.getStringExtra("Content"));
//		Time.setText(intent.getStringExtra("Time"));
//		StudyCount.setText("此课程已被" + intent.getStringExtra("StudyCount")+"次学习");
//		
		ImgShow.display(CourseImg, course.getCourseImg());
		
		final String videoUrl = course.getVideoAdress();
		
		OnClickListener playClickListener = new OnClickListener() {
			
			@Override
			public void onClick(View v) {


				if(course.getCourseType() == course.VIDEO_COURSE){
					Intent intent = new Intent(CourseDetailActivity.this, VideoPlayerActivity.class);
					intent.putExtra("VideoAdress", getVideoUrl(course.getVideoAdress()));
					intent.putExtra("CourseID", Integer.toString(course.getCourseID()));
					CourseDetailActivity.this.startActivity(intent);

				}else if(course.getCourseType() == course.URL_COURSE){

					Intent intent = new Intent(CourseDetailActivity.this, WebViewActivity.class);
					intent.putExtra("url", course.getURL());
					CourseDetailActivity.this.startActivity(intent);

				}else if(course.getCourseType() == course.SINGLE_IMG_COURSE){

                    Intent intent = new Intent(CourseDetailActivity.this, CourseDetailSingleImageActivity.class);
                    intent.putExtra("imgUrl", course.getContent());
                    CourseDetailActivity.this.startActivity(intent);

                }

                //test
//                Intent intent = new Intent(CourseDetailActivity.this, CourseDetailSingleImageActivity.class);
////                intent.putExtra("imgUrl", course.getCourseImg());
//                intent.putExtra("imgUrl", "http://192.168.37.96/test11.jpg");
//                CourseDetailActivity.this.startActivity(intent);

				
				RecodeStudyTimes studyTimes = new RecodeStudyTimes(CourseDetailActivity.this);
				studyTimes.recodeOne(Integer.toString(course.getCourseID()));
			}
		};
		
		play.setOnClickListener(playClickListener);
		CourseImg.setOnClickListener(playClickListener);

        //如果是url课件， 隐藏下载
        if(course.getCourseType() == DS_Course.URL_COURSE){
            download.setVisibility(View.GONE);
        }else{
            download.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CourseDownloader downloader = CourseDownloader.Create(CourseDetailActivity.this);
                    downloader.Download(course);
                }
            });
        }


		favorite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				favorCourse();
				
			}
		});
	}

	
	
	protected void favorCourse() {
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_FavoriteCourse.params.UserID, MyApplication.myUserID);
		params.put(HIF_FavoriteCourse.params.CourseID, thisCourseID);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_FavoriteCourse.address, params, new MyAjaxCallBack<Object>(this) {

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				HIF_FavoriteCourse.result result = 
						JsonUtil.fromJson((String)t, HIF_FavoriteCourse.result.class);
				
				if(result != null){
					if(result.result == 1){
						showToast("收藏成功！");

                        favorite_num.setText("收藏(" + (course.getFavoriteNum()+1)+")");

					}else{
						showToast("收藏失败："+"已收藏过此课程！");
					}
				}
			}
			
		});
	}

	protected void getComment(String CourseID) {
		
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetCoumment.params.CourseID, CourseID);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetCoumment.address, params, new AjaxCallBack<Object>() {

			
			@Override
			public void onFailure(Throwable t, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, strMsg);
				
				lodingView.setVisibility(View.GONE);
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
//				HIF_GetCourse.result result = JsonUtil.fromJson((String)t, HIF_GetCourse.result.class);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Comment>>(){}.getType();
				commentList  = gson.fromJson((String)t, listType);
				
				if(commentList != null){
					getView(commentList);
				}
				
				lodingView.setVisibility(View.GONE);
			}
			
		});
		
	}

	public void getView(List<DS_Comment> list){
		commentAdapter = new CommentAdapter(CourseDetailActivity.this, list);
		commentListView.setAdapter(commentAdapter);
	}
	
	public void submitComment(View v){
		if(WidgetAnim.checkIfEmpty(this, commentEdit)){
			return;
		}
		
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_SubmitComment.params.CourseID, thisCourseID);
		params.put(HIF_SubmitComment.params.UserID, MyApplication.myUserID);
		params.put(HIF_SubmitComment.params.UserHeadImg, MyApplication.myInfo.getHeadUrl());
		params.put(HIF_SubmitComment.params.CommentText, commentEdit.getText().toString());
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_SubmitComment.address, params, new MyAjaxCallBack<Object>(this) {

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				HIF_SubmitComment.result result = JsonUtil.fromJson((String)t, HIF_SubmitComment.result.class);
				
				if(result != null){
					if(result.result == 1){
						showToast("发表评论成功！");
						commentEdit.setText("");
						getComment(thisCourseID);
					}
				}
				
			}
			
		});
	}
}
